<?php

namespace App\Library\Wechat;

use App\Exceptions\WechatException;
use Exception;

class WechatApi extends BaseWechatApi
{
    const GRANT_TYPE_ACCESS_TOKEN = 'authorization_code'; // 获取access_token 的类型标识


    /**
     * 获取授权登录token
     *
     * @param string $code
     * @return array
     * @throws WechatException
     * @throws Exception
     */
    public function jsCode2Session(string $code): array
    {
        $params = [
            'js_code' => $code,
            'grant_type' => self::GRANT_TYPE_ACCESS_TOKEN,
            'appid' => self::$appId,
            'secret' => self::$appSecret,
        ];

        $apiUrl = $this->makeUrl(self::GET_APPLET_JS_CODE2SESSION);

        $result = $this->curlGet($apiUrl, $params);
        if (isset($result['errcode']) && $result['errcode'] != 0) {
            throw new WechatException('登录授权失败,error:' . json_encode($result), WechatException::CODE_1001);
        }
        return [
            'openid' => $result['openid'],
            'unionid' => $result['unionid'] ?? '',
        ];
    }
}
